package org.qfbl.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws Exception {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        Selector selector = Selector.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false) ;
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        while (true){
            if(selector.select(1000) == 0){
                System.out.println("服务器等待了一秒钟，无连接");
                continue;
            }
            //
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()){
                SelectionKey key = keyIterator.next();
                if(key.isAcceptable()){
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功，生成了一个socketChnnel" + socketChannel.hashCode());
                    //将socketChannel注册到selector，关注事件为op_read，同时给SockedtChannel关联一个byteBuffer
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024)) ;


                }
                if(key.isReadable()){

                    SocketChannel socketChannel = (SocketChannel) key.channel();
                    socketChannel.configureBlocking(false) ;
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    socketChannel.read(buffer);
                    System.out.println(buffer.capacity());
                    System.out.println("客户端发送过来的数据为："+ new String(buffer.array()));
                }
                keyIterator.remove();

            }


        }
    }
}
